from django.utils.deprecation import MiddlewareMixin
from django.http import HttpResponse
from . import models, utils

class LoginToken(MiddlewareMixin):
    def process_request(self, req):

        # 允许跨域
        if req.method == "OPTIONS":
            resp = HttpResponse('')
            resp['Access-Control-Allow-Origin'] = '*'
            resp['Access-Control-Allow-Headers'] = '*'
            resp['X-Frame-Options'] = 'ALLOWALL'
            return resp

        # 过滤用户的user id
        path = req.path_info # 请求路径
        print('这是一个req 中间键', path)
        # 白名单不需要userID过滤
        whiteList = ['/log_in', '/log_up', '/upload_file', '/get_file_data','/get_image' ,'/favicon.ico', '/' ]
        if path not in whiteList and 'static' not in path:
            userID = req.META.get('HTTP_USERID')
            if userID:
                user = utils.check_token(userID)
                if not user:
                    print('no user', userID)
                    return HttpResponse("")
                else:
                    # 用户存在
                    setattr(req, 'user', user)  # 将用户传过去
            else:
                # 若请求没有useID，直接拒绝
                print('no userid', userID)
                return HttpResponse("")
        
    def process_response(self,request,response):
        # 添加响应头
        response['Access-Control-Allow-Origin'] = "*"
        # 允许自定义前端可以添加请求头 useid 字段
        response['Access-Control-Allow-Headers'] = "*"
        response['Access-Control-Allow-Methods'] = "*"
        response['Access-Control-Allow-Credentials']="true"
        # 允许X-frame
        response['X-Frame-Options'] = 'ALLOWALL'
        return response


